package Serialization;
import java.io.*;


    // 实现Serializable接口，标记该类可序列化
    class User implements Serializable {
        // 序列化版本号，建议显式声明，避免版本不一致问题
        private static final long serialVersionUID = 1L;

        private String name;
        private int age;
        // transient修饰的变量不会被序列化
        private transient String password;

        public User(String name, int age, String password) {
            this.name = name;
            this.age = age;
            this.password = password;
        }

        @Override
        public String toString() {
            return "User{name='" + name + "', age=" + age + ", password='" + password + "'}";
        }
    }

    public class SerializationDemo {
        public static void main(String[] args) {
            // 创建一个用户对象
            User user = new User("张三", 25, "123456");
            System.out.println("序列化前: " + user);

            try {
                // 1. 序列化：将对象写入文件
                FileOutputStream fileOut = new FileOutputStream("user.ser");
                ObjectOutputStream out = new ObjectOutputStream(fileOut);
                out.writeObject(user);
                out.close();
                fileOut.close();
                System.out.println("对象已序列化到文件");

                // 2. 反序列化：从文件恢复对象
                FileInputStream fileIn = new FileInputStream("user.ser");
                ObjectInputStream in = new ObjectInputStream(fileIn);
                User deserializedUser = (User) in.readObject();
                in.close();
                fileIn.close();
                System.out.println("从文件反序列化后: " + deserializedUser);

            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

